package com.xiaoxin.xinlikesystem.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxin.xinlikesystem.exception.BusinessException;
import com.xiaoxin.xinlikesystem.exception.ErrorCode;
import com.xiaoxin.xinlikesystem.exception.ThrowUtils;
import com.xiaoxin.xinlikesystem.model.dto.user.UserQueryRequest;
import com.xiaoxin.xinlikesystem.model.entity.User;
import com.xiaoxin.xinlikesystem.model.enums.UserRoleEnum;
import com.xiaoxin.xinlikesystem.model.vo.user.LoginUserVO;
import com.xiaoxin.xinlikesystem.model.vo.user.UserVO;
import com.xiaoxin.xinlikesystem.service.UserService;
import com.xiaoxin.xinlikesystem.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.xiaoxin.xinlikesystem.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author Xiaoxin
 * @description 针对表【user(系统-用户表)】的数据库操作Service实现
 * @createDate 2025-05-10 13:59:19
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @return 新用户 id
     */
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword, checkPassword), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "用户账号过短");
        ThrowUtils.throwIf(userPassword.length() < 8 || checkPassword.length() < 8, ErrorCode.PARAMS_ERROR, "用户密码过短");
        ThrowUtils.throwIf(!userPassword.equals(checkPassword), ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");

        // 2. 检查是否重复（采用lambdaQueryWrapper，避免硬编码）
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, userAccount);
        long count = this.count(queryWrapper);
        ThrowUtils.throwIf(count > 0, ErrorCode.PARAMS_ERROR, "账号重复");

        // 3. 密码加密
        String encryptPassword = getEncryptPassword(userPassword);

        // 4. 保存用户数据到数据库
        User user = new User();
        user.setAccount(userAccount);
        user.setPassword(encryptPassword);
        user.setName("派大星");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");

        // 5. 返回用户id，主键回填
        return user.getId();
    }


    /**
     * 用户登录
     *
     * @param userAccount  用户账户
     * @param userPassword 用户密码
     * @param request      请求
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "账号错误");
        ThrowUtils.throwIf(userPassword.length() < 8, ErrorCode.PARAMS_ERROR, "密码错误");

        // 2. 加密
        String encryptPassword = getEncryptPassword(userPassword);

        // 3. 查询用户是否存在(使用LambdaQueryWrapper，避免硬编码)
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, userAccount);
        queryWrapper.eq(User::getPassword, encryptPassword);
        User user = this.getOne(queryWrapper);
        // 3.1 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }

        // 4. 记录用户登录态到 sa-token
        // 4.1 获取用户登陆设备
        String client = "pc";
        String ua = request.getHeader("User-Agent").toLowerCase();
        if (ua.contains("android") || ua.contains("iphone") || ua.contains("ipad") || ua.contains("mobile")) {
            client = "mobile";
        }
        // 4.3 多端登录：踢掉该端已有登录（同端互斥），并重新进行登录；如未登录则直接登录
        StpUtil.kickout(user.getId(), client);
        StpUtil.login(user.getId(), client);
        // 4.4 绑定到token上的会话
        // request.getSession().setAttribute(USER_LOGIN_STATE, user);
        StpUtil.getSession().set(USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }


    /**
     * 用户注销
     *
     * @param request 请求
     * @return 注销是否成功
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 1. 先判断用户是否登录(返回的为Json为 JSONObject 类型)
        ThrowUtils.throwIf(!StpUtil.isLogin(), ErrorCode.NOT_LOGIN_ERROR);

        // 2 获取用户登陆设备
        String client = "pc";
        String ua = request.getHeader("User-Agent").toLowerCase();
        if (ua.contains("android") || ua.contains("iphone") || ua.contains("ipad") || ua.contains("mobile")) {
            client = "mobile";
        }

        // 2. 移除登录态（该方法删除 token认证状态、对应会话、缓存信息（手动放入的USER_LOGIN_STATE）、Redis中对应的存储信息）
        StpUtil.logout(StpUtil.getLoginId(), client);
        return true;
    }


    /**
     * 获取当前登录用户
     *
     * @param request 请求
     * @return 登录用户信息
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 1. 先判断用户是否登录(返回的为Json为 JSONObject 类型)
        ThrowUtils.throwIf(!StpUtil.isLogin(), ErrorCode.NOT_LOGIN_ERROR);

        // 2. 从数据库查询（追求性能可以直接返回上述结果）
        long userId = StpUtil.getLoginIdAsLong();
        User currentUser = this.getById(userId);
        ThrowUtils.throwIf(currentUser == null, ErrorCode.NOT_LOGIN_ERROR);
        StpUtil.getSession().set(USER_LOGIN_STATE, currentUser);
        return currentUser;
    }


    /**
     * 获得脱敏后的登录用户信息
     *
     * @param user 用户信息
     * @return 脱敏后的用户信息
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user, loginUserVO);
        return loginUserVO;
    }


    /**
     * 获取加密后的密码
     *
     * @param userPassword 密码
     * @return 加密后的密码
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = "xiaoxin666";
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }


    /**
     * 获取查询条件
     * @param userQueryRequest 用户查询请求
     * @return 查询结果
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        // 1. 校验
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR, "请求参数为空");

        // 2. 参数获取
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getAccount();
        String userName = userQueryRequest.getName();
        String userProfile = userQueryRequest.getProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();

        // 3. 构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "account", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "name", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "profile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    /**
     * 获取脱敏后的用户信息
     *
     * @param user 用户信息
     * @return 脱敏后的用户列表
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }


    /**
     * 获取脱敏后的用户列表
     *
     * @param userList 用户信息列表
     * @return 脱敏后的用户列表
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }
}




